import os
import re
import uuid
import requests


# 地址转换规则：转换至同路径下同文件名称的文件夹内
def download_image(url, folder_path):
    if not url.startswith('http'):
        print("not http url, skip:" + url)
        return None
    response = requests.get(url)
    if response.status_code == 200:
        image_name = f"{uuid.uuid4()}.jpg"
        image_path = os.path.join(folder_path, image_name)
        with open(image_path, 'wb') as f:
            f.write(response.content)
        return image_name
    else:
        return None


def process_md_file(md_path):
    print("start download: " + md_path)
    with open(md_path, 'r', encoding='utf-8') as file:
        content = file.read()
    img_folder_path = os.path.join(os.path.dirname(md_path), "res", os.path.basename(md_path))
    pathCheck(img_folder_path)
    pattern = r'!\[(.*?)\]\((.*?)\)'
    matches = re.findall(pattern, content)
    for _, img_url in matches:
        img_name = download_image(img_url, img_folder_path)
        if img_name:
            local_img_path = os.path.join("res", os.path.basename(md_path), img_name)
            content = content.replace(img_url, local_img_path)
    with open(md_path, 'w', encoding='utf-8') as file:
        file.write(content)


def find_md_files(directory):
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith('.md'):
                yield os.path.join(root, file)


def pathCheck(path):
    if not os.path.exists(path):
        os.makedirs(path)


source_dir = input("Enter the directory path containing markdown files: ")

for md_file in find_md_files(source_dir):
    process_md_file(md_file)
